import Axios from 'axios';
import type { AxiosInstance, AxiosResponse } from 'axios';
import { getStorage } from '@/utils/cache';

const axiosinstance: AxiosInstance = Axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  headers: {
    'Content-Type': 'application/json'
  },
  responseType: 'json'
});

axiosinstance.interceptors.request.use((config) => {
  const newCif = { ...config };
  const Token = getStorage<string>('token');
  if (Token && newCif.headers) {
    newCif.headers.satoken = `${Token}`;
  }
  return newCif;
});

axiosinstance.interceptors.response.use(
  async (response: AxiosResponse<any>) => {
    try {
      if (response.config.responseType === 'arraybuffer') {
        return Promise.resolve(response);
      } else {
        const { data } = response;
        if (!data.success || data.code !== 200) {
          return Promise.reject(response);
        }
        return Promise.resolve(response);
      }
    } catch (err) {
      return Promise.reject(err);
    }
  }
);

export default axiosinstance;
